import 'package:collection/wrappers.dart';
import 'package:e_reception_flutter/common_widgets/common_constraint_box_widget/common_constraint_max_width_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_more_menu_dialog/common_more_menu_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_title_edit_with_underline_widget/common_title_edit_with_underline_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_title_edit_with_underline_widget/typeof/common_title_edit_with_underline_typeof.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/camera/front_camera_head/front_camera_head_page.dart';
import 'package:e_reception_flutter/ui/company/company_add_user_edit_info/bean/company_add_user_edit_info_type.dart';
import 'package:e_reception_flutter/ui/company/company_choose_terminal_list/bean/company_choose_terminal_response_bean.dart';
import 'package:e_reception_flutter/ui/company/company_choose_terminal_list/company_choose_terminal_list_page.dart';
import 'package:e_reception_flutter/ui/create_user/create_user/relative_stu/select_relative_stu_list_page.dart';
import 'package:e_reception_flutter/ui/create_user/edit_user/bean/edit_user_upload_bean.dart';
import 'package:e_reception_flutter/ui/create_user/user_course_class/class_course_widget.dart';
import 'package:e_reception_flutter/ui/create_user/user_course_class/course_class_bean/class_course_bean.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/cityWidget.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/create_user_address/add_and_remove_user_branch_page.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/create_user_address/create_user_address_attend_page.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/departmentWidget.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/multi_select_class_course_widget.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/multi_select_department_widget.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/personal_details_information_widget/add_user_address_page.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/projectWidget.dart';
import 'package:e_reception_flutter/ui/mypage/edit_name_dialog_widget.dart';
import 'package:e_reception_flutter/ui/person_detail/bean/person_detail_response_bean.dart';
import 'package:e_reception_flutter/utils/common_select_util.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_role_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/clip_image_head_border/clip_image_head_border_utils.dart';
import 'package:e_reception_flutter/vg_widgets/clip_image_head_border/logo_detail_page.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import '../edit_user_page.dart';

/// 添加用户编辑框组件
///
/// @author: zengxiangxi
/// @createTime: 3/10/21 10:41 AM
/// @specialDemand:
class EditUserEditWidget extends StatefulWidget {
  final EditUserUploadBean uploadBean;

  final ValueNotifier<String> updateNameValueNotifier;

  EditUserEditWidget(
      {Key key, this.uploadBean, this.updateNameValueNotifier})
      : super(key: key);

  @override
  _EditUserEditWidgetState createState() => _EditUserEditWidgetState();
}

class _EditUserEditWidgetState extends BaseState<EditUserEditWidget> {
  ///是否显示项目和城市
  bool isShowProjectAndCity = false;

  ///是否显示身份和终端
  bool isShowIdentityAndTerminal;

  TextEditingController _nameController;

  ///根据权限判断是否显示身份和终端
  bool isLastedIdentityAndTerminal;

  TextEditingController _identityController;
  TextEditingController _terminalController;
  TextEditingController _departmentController;
  TextEditingController _classController;
  // StreamSubscription editButtonSubscription;

  TextEditingController _addressController;

  bool editable = true;

  bool isCompany =
      UserRepository.getInstance().userData.companyInfo.isCompanyLike();

  FaceUserInfoBean faceUserInfoBean = FaceUserInfoBean();

  String addressStrInit;

  @override
  void initState() {
    super.initState();
    _departmentInit();
    isLastedIdentityAndTerminal =
        VgRoleUtils.isEditUserShowModifityRole(widget.uploadBean.userid);
    _nameController = TextEditingController();
    isShowIdentityAndTerminal = widget.uploadBean.isManagerTerminal ?? false;
    widget.uploadBean.isManagerTerminal = isShowIdentityAndTerminal;
    widget.updateNameValueNotifier?.addListener(_processUpdateName);
    _identityController=TextEditingController(text: '');
    _terminalController = TextEditingController(text: "");
    _departmentController = TextEditingController(text: "");
    if((widget?.uploadBean?.listBranchBean?.length??0)!=0){
      if((widget?.uploadBean?.listBranchBean?.length??0)==1){
        addressStrInit = widget?.uploadBean?.listBranchBean[0]?.branchname;
      }else{
        addressStrInit = widget?.uploadBean?.listBranchBean[0].branchname+"等${widget?.uploadBean?.listBranchBean?.length}个地址";
      }
    }
    _addressController = TextEditingController(text:  addressStrInit??"");
    _classController = TextEditingController(text: "");
  }

  void _departmentInit(){
  faceUserInfoBean?.fuid = widget?.uploadBean?.fuid;
  faceUserInfoBean?.departmentid = widget?.uploadBean?.departmentId;
  faceUserInfoBean?.department = widget?.uploadBean?.departmentName;

  // editButtonSubscription =
  //     VgEventBus.global.on<EditOrSaveButtonTextEvent>().listen((event) {
  //       editable = false;
  //       setState(() { });
  //     });
  }

  void _processUpdateName() {
    final String updateName = widget.updateNameValueNotifier.value;
    if (_nameController == null) {
      return;
    }
    widget.uploadBean.nick = updateName;
    _nameController.text = _getNameAndNickSplitStr();
  }

  @override
  void dispose() {
    widget.updateNameValueNotifier.removeListener(_processUpdateName);
    _terminalController.dispose();
    _classController.dispose();
    _departmentController.dispose();
    _addressController?.dispose();
    // editButtonSubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      physics: NeverScrollableScrollPhysics(),
      child: Column(
        mainAxisSize: MainAxisSize.max,
        children: <Widget>[
          _toOneMineWidget(),
          // Spacer(),
          SizedBox(height: 10,),
          Visibility(
            //员工且不是自己时
              visible: (widget.uploadBean.groupBean.isStaff())&&(UserRepository.getInstance().userData.user.userid!=widget.uploadBean.userid),
              child: _toManagerTerminalBarWidget()),
        ],
      ),
    );
  }

  Widget _toOneMineWidget() {
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          SizedBox(height: 10),
          _toClassifyAndIdRowWidget(),
          Container(
              height: 10,
              color: ThemeRepository.getInstance().getBgOrSplitColor_191E31()),
          _toNameAndPhoneRowWidget(),
          Container(
              height: 10,
              color: ThemeRepository.getInstance().getBgOrSplitColor_191E31()),
          _toHideOrShowStaffWidget(),
          _toHideOrShowGradeWidget(),
          _toHideOrShowAssociateStudent(),
          if(UserRepository.getInstance().userData.companyInfo.isShowFaceRecognition())_toAddressWidget(),
        ],
      ),
    );
  }

  Widget _toHideOrShowStaffWidget() {
    return Offstage(
      offstage: !(widget.uploadBean.groupBean.isStaff() ?? false),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          _toDepartmentWidget(),
          Offstage(
            //是否直接展示部门城市
            offstage: true,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                _toSplitLineWidget(),
                // _toProjectWidget(),
                _toSplitLineWidget(),
                // _toCityWidget(),
              ],
            ),
          ),
          // _toMoreButtonWidget(),
        ],
      ),
    );
  }

  ///是否隐藏和显示班级
  Widget _toHideOrShowGradeWidget() {
    return Offstage(
      offstage: !(widget.uploadBean.groupBean.isStudent() ?? false),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          // _toCourseWidget(),
          // _toSplitLineWidget(),
          _toGradeWidget(),
        ],
      ),
    );
  }

  // Widget _toCourseWidget() {
  //   return _EditTextWidget(
  //     title: "课程",
  //     hintText: "请选择",
  //     isShowGoIcon: true,
  //     onTap: (String editText, dynamic value) {
  //       return CourseClassWidget.navigatorPush(context);
  //     },
  //     onDecodeResult: (dynamic result) {
  //       if (result is! EditTextAndValue) {
  //         return null;
  //       }
  //       return result;
  //     },
  //     onChanged: (String editText, dynamic value) {
  //       widget.uploadBean.courseId = value;
  //       widget.uploadBean.courseName = editText;
  //     },
  //   );
  // }

  Widget _toHideOrShowAssociateStudent(){
    // PersonDetailResponseBean personDetailResponseBean = PersonDetailResponseBean();
    // personDetailResponseBean?.data?.faceUserInfo = faceInfoBean;
    List<StudentInfoBean> showStudentInfo = widget.uploadBean.editStudentInfo.cast<StudentInfoBean>();//展示
    List<StudentInfoBean> studentInfo = widget.uploadBean.studentInfo.cast<StudentInfoBean>();//保存
    // //获取关联学员信息
    List<String> listStudentName = new List<String>();
    List<String> listStudentFuid = new List<String>();
    GroupListBean groupListBean = GroupListBean();
    String studentNameStr = "";
    String groupidStudent = "";
    if (widget?.uploadBean?.groupBean?.groupName == "家长") {
      if(UserRepository.getInstance().userData.comUser.roleid == "99"){
        studentInfo?.forEach((element) {
          if(element?.nick!=null && element?.nick!=""){
            listStudentName?.add("${element?.name}/${element?.nick}");
          }else{
            listStudentName?.add(element?.name);
          }
          listStudentFuid?.add(element?.fuid);
          groupidStudent = element?.groupid;
        });
      }else{
        showStudentInfo?.forEach((element) {
          if(element?.nick!=null && element?.nick!=""){
            listStudentName?.add("${element?.name}/${element?.nick}");
          }else{
            listStudentName?.add(element?.name);
          }
          listStudentFuid?.add(element?.fuid);
          groupidStudent = element?.groupid;
        });
      }

      studentNameStr = VgStringUtils.getSplitStr(listStudentName, symbol: "、");
      // widget.uploadBean?.splitDepartment();
    }
    return Offstage(
      offstage: !(widget.uploadBean.groupBean.isParent() ?? false),
      child: _EditTextWidget(
        title: "关联学员",
        hintText: "请选择",
        isShowGoIcon: editable,
        // readOnly: true,
        initContent: studentNameStr ?? "未设置",
        onTap: (String editText, dynamic value) {
          UserRepository.getInstance().userData?.companyInfo?.groupList?.forEach((element) {

            if(element?.groupType == "02"){
              groupListBean?.groupid = element?.groupid;
              groupListBean?.groupType = element?.groupType;
            }
          });
          return  SelectRelativeStuListPage.navigatorPush(
              context, listStudentFuid, groupListBean, widget?.uploadBean?.fuid,studentInfo:studentInfo);

        },
        onDecodeResult: (dynamic result) {
          if (result == null) {
            return null;
          }
          return EditTextAndValue(
              value: result["ids"],
              editText: result["name"]);
              // editText: (result?.length ?? 0) <= 0 ? "" : "${result.length}个学员");
        },
        onChanged: (String editText, dynamic value) {
          studentNameStr = editText;
        },
      ),
    );
  }

  Widget _toGradeWidget() {
    return _EditTextWidget(
      title: "所在班级",
      hintText: "请选择",
      // readOnly: true,
      isShowGoIcon: editable,
      initContent: widget?.uploadBean?.splitManagerClassName(widget.uploadBean.gradeName),
      onTap: (String editText, dynamic value) {
        return ClassCourseWidget.navigatorPush(
            context, widget.uploadBean.classList);
      },
      onDecodeResult: (dynamic result) {
        if (result is! List<ClassCourseListItemBean>) {
          return null;
        }
        List<ClassCourseListItemBean> resultList = result;
        String content = "";
        if((resultList?.length??0) == 1){
          content = resultList[0].name;
        }else if((resultList?.length??0) > 1){
          content = "${resultList.length}个班级";
        }
        return EditTextAndValue(
            value: result,
            editText: content,
        );
      },
      onChanged: (String editText, dynamic value) {
        widget.uploadBean.classList = value;
      },
    );
  }

  Widget _toNameAndPhoneRowWidget() {
    return Row(
      children: <Widget>[
        Expanded(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              _EditTextWidget(
                title: "姓名",
                hintText: "请输入",
                maxLength: 20,
                isFollowEdit: false,
                isShowRedStar: true,
                autofocus: false,
                // readOnly: editable,
                controller: _nameController,
                initContent: _getNameAndNickSplitStr(),
                onTap: StringUtils.isEmpty(widget.uploadBean.nick)
                    ? null
                    : (String editText, dynamic value) {
                        return EditNameDialogWidget.navigatorPushDialog(context,
                            widget.uploadBean.name, widget.uploadBean.nick);
                      },
                onDecodeResult: (dynamic result) {
                  if (result == null || result is! Map) {
                    return null;
                  }
                  widget.uploadBean.name =
                      result[EDIT_NAME_AND_NICK_BY_NAME_KEY];
                  widget.uploadBean.nick =
                      result[EDIT_NAME_AND_NICK_BY_NICK_KEY];
                  _nameController.text = _getNameAndNickSplitStr();
                  return null;
                },
                onChanged: (String editText, dynamic value) {
                  widget.uploadBean.name = editText;
                  widget.uploadBean.nick = value;
                },
              ),
              _toSplitLineWidget(),
              _EditTextWidget(
                title: "手机",
                hintText: "请输入",
                // readOnly: editable,
                keyboardType: TextInputType.number,
                inputFormatters: [
                  WhitelistingTextInputFormatter(RegExp("[0-9+]")),
                  LengthLimitingTextInputFormatter(DEFAULT_PHONE_LENGTH_LIMIT)
                ],
                initContent: widget.uploadBean.phone,
                isShowRedStar: widget.uploadBean.phoneRedStar(),
                onChanged: (String editText, dynamic value) {
                  widget.uploadBean.phone = editText;
                },
              ),
            ],
          ),
        ),
        SizedBox(
          width: 15,
        ),
        GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
              onClickUserLogo();
          },
          child: ClipRRect(
            borderRadius: BorderRadius.circular(2),
            child: Container(
              width: 90,
              height: 90,
              child: StringUtils.isNotEmpty(widget.uploadBean.headFaceUrl)
                  ? VgCacheNetWorkImage(
                      widget.uploadBean.headFaceUrl,
                      imageQualityType: ImageQualityType.middleUp,
                      defaultErrorType: ImageErrorType.head,
                      defaultPlaceType: ImagePlaceType.head,
                    )
                  : Image.asset("images/create_user_head_ico.png"),
            ),
          ),
        ),
        SizedBox(width: 15),
      ],
    );
  }

  void onClickUserLogo() {
    FocusScope.of(context).requestFocus(FocusNode());
    if (StringUtils.isNotEmpty(widget.uploadBean.headFaceUrl)) {
      LogoDetailPage.navigatorPush(context,
          url: widget.uploadBean.headFaceUrl,
          selectMode: SelectMode.HeadBorder,
          clipCompleteCallback: (path, cancelLoadingCallback) {
            widget.uploadBean.headFaceUrl = path;
            setState(() {});
          }
      );
      return;
    }
    addUserLogo();
  }

  void addUserLogo() {
    CommonMoreMenuDialog.navigatorPushDialog(context, {
      "上传图片": () async {
        String path = await ClipImageHeadBorderUtil.clipOneImage(context,
            scaleY: 1, scaleX: 1, maxAutoFinish: true,
            isShowHeadBorderWidget: true);
        if (path == null || path == "") {
          return;
        }
        widget.uploadBean.headFaceUrl = path;
        setState(() {});
      },
      "拍照": () async {
        String path = await FrontCameraHeadPage.navigatorPush(context);
        if (path == null || path.isEmpty) {
          return;
        }
        widget.uploadBean.headFaceUrl = path;
        setState(() {});
      }
    });
  }

  String _getNameAndNickSplitStr() {
    StringBuffer stringBuffer = StringBuffer();
    if (StringUtils.isNotEmpty(widget.uploadBean.nick)) {
      stringBuffer.write(VgStringUtils.subStringAndAppendSymbol(
          widget.uploadBean.name, 7,
          symbol: "..."));
    } else {
      stringBuffer.write(widget.uploadBean.name);
    }
    if (StringUtils.isNotEmpty(widget.uploadBean.nick)) {
      stringBuffer.write(" / ");
      stringBuffer.write(VgStringUtils.subStringAndAppendSymbol(
          widget.uploadBean.nick, 7,
          symbol: "..."));
    }
    return stringBuffer.toString();
  }

  ///分割线
  Widget _toSplitLineWidget() {
    return Container(
      padding: const EdgeInsets.only(left: 15),
      height: 0.5,
      child: Container(
        color: ThemeRepository.getInstance().getLineColor_3A3F50(),
      ),
    );
  }

  ///分类 家长不显示编号
  Widget _toClassifyAndIdRowWidget() {
    return Row(
      children: <Widget>[
        Expanded(
          child: _EditTextWidget(
            title: "分类",
            hintText: "请选择",
            // readOnly: editable,
            isShowRedStar: true,
            customWidget: (Widget titleWidget, Widget textFieldWidget,
                Widget leftWidget, Widget rightWidget) {
              return Row(
                children: <Widget>[
                  leftWidget,
                  Expanded(
                    child: GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      // onTap: () async {
                      //   GroupListBean groupListBean =
                      //       await CommonSelectItemForListPage.navigatorPush<
                      //               GroupListBean>(context,
                      //           title: "分类选择",
                      //           selectedItem: widget.uploadBean.groupBean,
                      //           list: UserRepository.getInstance()
                      //               .userData
                      //               ?.companyInfo
                      //               ?.groupList,
                      //           getTextFunc: (GroupListBean groupItemBean) {
                      //     return groupItemBean?.groupName;
                      //   });
                      //   if (groupListBean == null) {
                      //     return;
                      //   }
                      //   widget.uploadBean.groupBean = groupListBean;
                      //   setState(() {});
                      // },
                      child: Row(
                        children: <Widget>[
                          titleWidget,
                          CommonConstraintMaxWidthWidget(
                            maxWidth: ScreenUtils.screenW(context) / 4,
                            child: Text(
                              showOriginEmptyStr(
                                      widget.uploadBean.groupBean?.groupName) ??
                                  "请选择",
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                color: Color(0xFFD0E0F7),
                                fontSize: 14,
                              ),
                            ),
                          ),
                          (widget.uploadBean.groupBean?.isParent() ?? false)
                              ? Spacer()
                              : SizedBox(
                                  width: 0,
                                ),
                          // Padding(
                          //   padding: const EdgeInsets.only(
                          //       left: 15, right: 15, top: 2),
                          //   child: Image.asset(
                          //     "images/go_ico.png",
                          //     width: 6,
                          //     color: Color(0xFF5E687C),
                          //   ),
                          // ),
                        ],
                      ),
                    ),
                  )
                ],
              );
            },
          ),
        ),
        (widget.uploadBean.groupBean?.isParent() ?? false)
            ? SizedBox(
                width: 1,
              )
            : Expanded(
                //家长不显示编号
                child: _EditTextWidget(
                  title: "编号",
                  hintText: "员工号/学号等",
                  isShowRedStar: false,
                  isGoneRedStar: true,
                  // readOnly: editable,
                  initContent: widget.uploadBean.userNumber ?? '',
                  onChanged: (String editText, dynamic value) {
                    widget.uploadBean.userNumber = editText;
                  },
                ),
              )
      ],
    );
  }

  Widget _toDepartmentWidget() {
    return _EditTextWidget(
      title: "所在部门",
      hintText: "请选择",
      isShowGoIcon: editable,
      readOnly: true,
      initValue: faceUserInfoBean?.departmentid,
      initContent: faceUserInfoBean?.department,
      onTap: (String editText, dynamic value) {
        return DepartmentWidget.navigatorPush(
            context, widget.uploadBean?.departmentId,fuid:faceUserInfoBean?.fuid,selectOnly: true);

      // return PersonalDepartmentWidget.navigatorPush(context, faceUserInfoBean)
      //       .then((value) {
      //   faceUserInfoBean?.department = value?.editText;
      //   faceUserInfoBean?.departmentid = value?.value;
      //   });
      },
      onDecodeResult: (dynamic result) {
        if (result is! EditTextAndValue) {
          return null;
        }
        return result;
      },
      onChanged: (String editText, dynamic value) {
        widget.uploadBean.departmentId = value;
        widget.uploadBean.departmentName = editText;
        faceUserInfoBean?.departmentid = value;
        faceUserInfoBean?.department = editText;
      },
    );
  }

  Widget _toAddressWidget() {
    return _EditTextWidget(
      controller: _addressController,
      title: "刷脸地址",
      hintText: "请选择",
      isShowGoIcon: true,
      isShowRedStar: true,
      initContent: widget.uploadBean.address,
      onTap: (String editText, dynamic value) {
        return AddAndRemoveUserBranchPage.navigatorPush(
            context, widget?.uploadBean?.listBranchBean,
            widget?.uploadBean?.fuid, widget?.uploadBean?.fid,
            createEdit: true).then((value){
          AddRemoveAddressData data = value;
          if ((data?.addList?.isEmpty ?? true) && (data?.removeList?.isEmpty ?? true)) return;
          List<String> addCbids = [];
          data?.addList?.forEach((element) {
            if(element?.editSelected ?? false){
              addCbids?.add(element?.cbid);
            }
          });
          List<String> removeCbids = [];
          data?.removeList?.forEach((element) {
            if(element?.selected == false){
              removeCbids?.add(element?.cbid);
            }
          });
          if(widget?.uploadBean?.listBranchBean?.length == 1){
            _addressController?.text = widget?.uploadBean?.listBranchBean[0]?.branchname;
          }else{
            _addressController?.text = widget?.uploadBean?.listBranchBean[0].branchname+"等${widget?.uploadBean?.listBranchBean?.length}个地址";
          }
          widget.uploadBean.addCbids = VgStringUtils.getSplitStr(addCbids, symbol: ",");
          widget?.uploadBean?.removeCbids = VgStringUtils.getSplitStr(removeCbids, symbol: ",");
          // if(value != null && (widget?.uploadBean?.listBranchBean?.length ?? 0) != 0){
          //   widget?.uploadBean?.listBranchBean = value;
          //   List<String> addCbids = [];
          //   data?.addList?.forEach((element) {
          //     if(element?.editSelected??false){
          //       addCbids?.add(element?.cbid);
          //     }
          //   });
          //   List<String> removeCbids = [];
          //   value?.forEach((element) {
          //     if(element?.editSelected == false){
          //       removeCbids?.add(element?.cbid);
          //     }
          //   });
          //   // print("lz:${removeCbids}::${addCbids}:::${value}");
          //   if(value?.length == 1){
          //     _addressController?.text = widget?.uploadBean?.listBranchBean[0]?.branchname;
          //   }else{
          //     _addressController?.text = widget?.uploadBean?.listBranchBean[0].branchname+"等${value?.length}个地址";
          //   }
          //   widget.uploadBean.addCbids = VgStringUtils.getSplitStr(addCbids, symbol: ",");
          //   widget?.uploadBean?.removeCbids = VgStringUtils.getSplitStr(removeCbids, symbol: ",");
            // _addressController?.text = widget?.uploadBean?.listBranchBean[0]?.address+"等${value?.length}个地址";
          // }
        });
      },
      // onDecodeResult: (dynamic result) {
      //   if (result is! EditTextAndValue) {
      //     return null;
      //   }
      //   return result;
      // },
      // onChanged: (String editText, dynamic value) {
      //   widget.uploadBean.caid = value;
      //   widget.uploadBean.address = editText;
      // },
    );
  }

  Widget _toProjectWidget() {
    return _EditTextWidget(
      title: "所在项目",
      hintText: "请选择",
      isShowGoIcon: editable,
      readOnly: true,
      initValue: widget.uploadBean.projectId,
      initContent: widget.uploadBean.projectName,
      onTap: (String editText, dynamic value) {
        return ProjectWidget.navigatorPush(
            context, widget.uploadBean?.projectId);
      },
      onDecodeResult: (dynamic result) {
        if (result is! EditTextAndValue) {
          return null;
        }
        return result;
      },
      onChanged: (String editText, dynamic value) {
        widget.uploadBean.projectId = value;
        widget.uploadBean.projectName = editText;
      },
    );
  }

  Widget _toCityWidget() {
    return _EditTextWidget(
      title: "所在城市",
      hintText: "请选择",
      isShowGoIcon: editable,
      readOnly: true,
      initValue: widget.uploadBean.cityName,
      initContent: widget.uploadBean.cityName,
      onTap: (String editText, dynamic value) {
        return CityWidget.navigatorPush(context, widget.uploadBean?.cityId);
      },
      onDecodeResult: (dynamic result) {
        if (result is! EditTextAndValue) {
          return null;
        }
        return result;
      },
      onChanged: (String editText, dynamic value) {
        widget.uploadBean.cityId = editText;
        widget.uploadBean.cityName = editText;
      },
    );
  }

  ///更多按钮
  Widget _toMoreButtonWidget() {
    return Offstage(
      offstage: isShowProjectAndCity,
      child: GestureDetector(
        onTap: () {
          VgToolUtils.removeAllFocus(context);
          isShowProjectAndCity = true;
          setState(() {});
        },
        child: Container(
          color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
          padding: const EdgeInsets.only(top: 13, bottom: 30),
          child: Center(
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Text(
                  "更多信息",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Color(0xFF5E687C),
                    fontSize: 12,
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 3),
                  child: Icon(
                    Icons.keyboard_arrow_down,
                    color: Color(0xFF5E687C),
                    size: 14,
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _toManagerTerminalBarWidget() {
    return Container(
      constraints: BoxConstraints(minHeight: !isCompany ? 280 : 250),
      child: Column(
        mainAxisSize: MainAxisSize.max,
        children: <Widget>[
          Container(
            height: 50,
            color: ThemeRepository.getInstance().getCardBgColor_21263C(),
            child: Row(
              children: <Widget>[
                SizedBox(width: 15),
                Text(
                  "管理权限",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Color(0xFFBFC2CC),
                    fontSize: 15,
                  ),
                ),
                Spacer(),
                GestureDetector(
                  behavior: HitTestBehavior.translucent,
                  onTap: () {
                    isShowIdentityAndTerminal = !isShowIdentityAndTerminal;
                    widget.uploadBean.isManagerTerminal = isShowIdentityAndTerminal;
                    if (!isShowIdentityAndTerminal) {
                      resetManagerData();
                    }else{
                      widget.uploadBean.identityType = CompanyAddUserEditInfoIdentityType.commonAdmin;
                      widget.uploadBean.identityName =
                          CompanyAddUserEditInfoIdentityExtension.getIdToTypeStr(
                              '90')
                              .getTypeToStr();
                      _identityController.text = widget.uploadBean.identityName;
                    }
                    setState(() {});
                    VgToolUtils.removeAllFocus(context);
                  },
                  child: Padding(
                    padding: const EdgeInsets.all(15.0),
                    child: Image.asset(
                      isShowIdentityAndTerminal
                          ? "images/switch_open.png"
                          : "images/switch_close.png",
                      width: 36,
                      gaplessPlayback: true,
                    ),
                  ),
                )
              ],
            ),
          ),
          Offstage(
            offstage: !isShowIdentityAndTerminal,
            child: Container(
              color: ThemeRepository.getInstance().getCardBgColor_21263C(),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  _toIdentityWidget(),
                  _toCommonAdminTermainlWidget(), //管理终端
                  _toManageDepartmentWidget(), //管理部门
                  _toManageClassWidget() //管理班级
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  ///管理级别
  Widget _toIdentityWidget() {
    return _EditTextWidget(
      title: "管理级别",
      hintText: "请选择",
      readOnly: true,
      controller: _identityController,
      isShowGoIcon: editable,
      isShowRedStar: true,
      initContent: widget.uploadBean.identityName,
      onTap: (String editText, dynamic value) {
        // if(editable)return null;
        return SelectUtil.showListSelectDialog(
          context: context,
          title: "管理级别",
          positionStr: widget.uploadBean.identityName,
          textList: CompanyAddUserEditInfoIdentityExtension.getListStr(),
        );
      },
      onDecodeResult: (dynamic result) {
        if (result is String && StringUtils.isNotEmpty(result)) {
          return EditTextAndValue(
              editText: result,
              value:
                  CompanyAddUserEditInfoIdentityExtension.getStrToType(result));
        }
        return null;
      },

      onChanged: (String editText, dynamic value) {
        widget.uploadBean.identityName = editText;
        widget.uploadBean.identityType = value;
        widget.uploadBean.departmentList = null;
        widget.uploadBean.classIdList = null;
        widget.uploadBean.terminalList = null;
        if (value == CompanyAddUserEditInfoIdentityType.superAdmin) {
          //超管时清空终端 部门 班级 （不用上传）
          // VgEventBus.global.send(SuperAdminRefreshEven());
          // setState(() { });
          _terminalController.text = "全部终端";
          _departmentController.text = "全部部门";
          _classController.text = "全部班级";
        }else{
          _terminalController.text = "";
          _departmentController.text = "";
          _classController.text = "";
        }
        setState(() {

        });

      },
    );
  }

  ///管理终端
  Widget _toCommonAdminTermainlWidget() {
    return Column(
      children: <Widget>[
        _toSplitLineWidget(),
        _EditTextWidget(
          title: "管理终端",
          readOnly: true,
          controller: _terminalController,
          hintText: widget.uploadBean.isSuperAdminRole() ? "全部${widget?.uploadBean?.terminalList?.length??0}台终端显示屏" : "请选择",
          isShowGoIcon: !widget.uploadBean.isSuperAdminRole(),
          initContent: widget.uploadBean.isSuperAdminRole()
              ? "全部${widget?.uploadBean?.terminalList?.length??0}台终端显示屏"
              : _getTerminalEditValueStr(widget.uploadBean.terminalList),
          isShowRedStar: false,
          onTap: (String editText, dynamic value) {
            // if(editable)return null;
            if (widget.uploadBean.isSuperAdminRole()) {
              return null;
            }
            return CompanyChooseTerminalListPage.navigatorPush(
                context, widget?.uploadBean?.terminalList);
          },
          onDecodeResult: (dynamic result) {
            if (result is! List<CompanyChooseTerminalListItemBean>) {
              return null;
            }
            List<CompanyChooseTerminalListItemBean> resultList = result;

            EditTextAndValue editTextAndValue = EditTextAndValue(
              editText: _getTerminalEditValueStr(resultList),
              value: result,
            );
            return editTextAndValue;
          },
          onChanged: (String editText, dynamic value) {
            setState(() {
              widget?.uploadBean?.terminalList = value;
            });
          },
        ),
      ],
    );
  }

  ///管理部门
  Widget _toManageDepartmentWidget() {
    return Column(
      children: <Widget>[
        _toSplitLineWidget(),
        _EditTextWidget(
            title: "管理部门",
            readOnly: true,
            controller: _departmentController,
            hintText: widget.uploadBean.isSuperAdminRole() ? "全部${widget?.uploadBean?.departmentList?.length??0}个部门" : "请选择",
            initContent: widget.uploadBean.isSuperAdminRole()
                ? "全部${widget?.uploadBean?.departmentList?.length??0}个部门"
                : widget.uploadBean.managerDepartmentName,
            isShowGoIcon: !widget.uploadBean.isSuperAdminRole(),
            isShowRedStar: false,
            onTap: (String editText, dynamic value) {
              // if(editable)return null;
              if (widget.uploadBean.isSuperAdminRole()) {
                return null;
              }
              return MultiSelectDepartmentWidget.navigatorPush(context,
                  selectIds: widget.uploadBean?.departmentList,
                  multiSelect: true);
            },
            onDecodeResult: (dynamic result) {
              if (result is! EditTextAndValue) {
                return null;
              }
              return result;
            },
            onChanged: (String editText, dynamic value) {
              _departmentController.text = widget.uploadBean?.splitDepartment(editText);
              widget.uploadBean.managerDepartmentName = editText;
              widget.uploadBean?.departmentList = value;
              setState(() {

              });
            }),
      ],
    );
  }

  ///管理班级
  _toManageClassWidget() {
    return Visibility(
      visible: !isCompany,
      child: Column(
        children: <Widget>[
          _toSplitLineWidget(),
          _EditTextWidget(
              title: "管理班级",
              readOnly: true,
              hintText: widget.uploadBean.isSuperAdminRole() ? "全部${widget?.uploadBean?.classIdList?.length??0}个班级" : "请选择",
              controller: _classController,
              initContent: widget.uploadBean.isSuperAdminRole()
                  ? "全部${widget?.uploadBean?.classIdList?.length??0}个班级"
                  : widget.uploadBean.managerClassName,
              isShowGoIcon: !widget.uploadBean.isSuperAdminRole(),//只读不显示
              isShowRedStar: false,
              onTap: (String editText, dynamic value) {
                // if(editable)return null;
                if (widget.uploadBean.isSuperAdminRole()) {
                  return null;
                }
                return MultiSelectClassCourseWidget.navigatorPush(
                    context, widget.uploadBean.classIdList);
              },
              onDecodeResult: (dynamic result) {
                if (result is! EditTextAndValue) {
                  return null;
                }
                return result;
              },
              onChanged: (String editText, dynamic value) {
                _classController.text = widget?.uploadBean?.splitManagerClassName(editText);
                widget.uploadBean.managerClassName = editText;
                widget.uploadBean?.classIdList = value;
                setState(() {

                });
              }),
        ],
      ),
    );
  }

  ///获取终端编辑值串
  String _getTerminalEditValueStr(
      List<CompanyChooseTerminalListItemBean> resultList) {
    String editTextStr;
    if (resultList == null || resultList.isEmpty) {
      editTextStr = "";
    } else if (resultList.length == 1) {
      editTextStr = resultList?.elementAt(0)?.getTerminalName(0);
      //处理空名字
      if (StringUtils.isEmpty(editTextStr)) {
        editTextStr = "1个终端";
      }
    } else {
      editTextStr = "${resultList?.length ?? 0}个终端";
    }
    return editTextStr;
  }

  ///管理级别、终端、部门等清空
  void resetManagerData() {
    widget.uploadBean.departmentList = null;
    widget.uploadBean.classIdList = null;
    widget.uploadBean.terminalList = null;
    _terminalController.text = "";
    _departmentController.text = "";
    _classController.text = "";
    _identityController.text="";
    widget.uploadBean.identityType =
        CompanyAddUserEditInfoIdentityType.commonUser;
  }
}

/// 编辑框组件
///
/// @author: zengxiangxi
/// @createTime: 1/18/21 10:55 PM
/// @specialDemand:
class _EditTextWidget extends StatelessWidget {
  final String title;

  final String hintText;

  final CommonTitleEditEditAndValueChangedCallback onChanged;

  ///点击
  final CommonTitleNavigatorPushCallback onTap;

  ///解析跳转返回值
  final CommonTitlePopResultDecodeCallback onDecodeResult;

  final bool isShowRedStar;

  ///中字极限
  final int maxZHCharLimit;

  ///极限字数回调
  final ValueChanged<int> limitCharFunc;

  ///限制
  final List<TextInputFormatter> inputFormatters;

  ///是否显示跳转icon
  final bool isShowGoIcon;

  ///初始化数据
  final String initContent;

  ///初始值
  final dynamic initValue;

  ///只读
  final bool readOnly;

  ///是否去掉红星
  final bool isGoneRedStar;

  ///是否跟随编辑框
  final bool isFollowEdit;

  final bool autofocus;

  final TextInputType keyboardType;

  final maxLength;

  final TextEditingController controller;

  final Function(Widget titleWidget, Widget textFieldWidget, Widget leftWidget,
      Widget rightWidget) customWidget;

  const _EditTextWidget(
      {Key key,
      this.title,
      this.hintText,
      this.onChanged,
      this.isShowRedStar = false,
      this.onTap,
      this.onDecodeResult,
      this.maxZHCharLimit,
      this.limitCharFunc,
      this.inputFormatters,
      this.isShowGoIcon = false,
      this.initContent,
      this.initValue,
      this.readOnly,
      this.isGoneRedStar = false,
      this.isFollowEdit = false,
      this.customWidget,
      this.controller,
      this.keyboardType, this.autofocus = false, this.maxLength})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CommonTitleEditWithUnderlineWidget(
      controller: controller,
      titleTextStyle: TextStyle(
          color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
          fontSize: 14),
      editTextStyle: TextStyle(
          color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
          fontSize: 14),
      title: title,
      titleMarginRight: 15,
      height: 50,
      onChanged: onChanged,
      autofocus: autofocus,
      onDecodeResult: onDecodeResult,
      onTap: onTap,
      minLines: 1,
      maxLines: 1,
      maxLength: maxLength,
      readOnly: readOnly,
      maxZHCharLimit: maxZHCharLimit,
      limitCharFunc: limitCharFunc,
      inputFormatters: inputFormatters,
      customWidget: customWidget,
      keyboardType: keyboardType,
      lineMargin: const EdgeInsets.only(left: 15, right: 0),
      lineUnselectColor: Color(0xFF303546),
      lineHeight: 0,
      initContent: initContent,
      initValue: initValue,
      lineSelectedColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      hintText: hintText,
      autoDispose: false,
      hintTextStyle: TextStyle(
          color: ThemeRepository.getInstance().getTextEditHintColor(),
          fontSize: 14),
      rightWidget: Offstage(
        offstage: !isShowGoIcon,
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 15),
          child: Image.asset(
            "images/go_ico.png",
            width: 6,
            color: Color(0xFF5E687C),
          ),
        ),
      ),
      leftWidget: Offstage(
        offstage: isGoneRedStar,
        child: Container(
          width: 15,
          child: Opacity(
            opacity: isShowRedStar ? 1 : 0,
            child: Center(
              child: Padding(
                padding: const EdgeInsets.only(top: 5),
                child: Text(
                  "*",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: ThemeRepository.getInstance()
                          .getMinorRedColor_F95355(),
                      fontSize: 14,
                      height: 1.1),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}


class SuperAdminRefreshEven{}